package com.usian.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.contants.wemedia.WemediaContans;
import com.usian.common.exception.CatchCustomException;
import com.usian.common.exception.code.UserStatusCode;
import com.usian.model.admin.dtos.NewsAuthDto;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.model.media.vo.WmNewsVo;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.mapper.WmUserMapper;
import com.usian.wemedia.service.WmNewsService;
import org.apache.ibatis.javassist.bytecode.stackmap.BasicBlock;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service
@SuppressWarnings("ALL")
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Override
    public ResponseResult findAll(WmNewsPageReqDto wmNewsPageReqDto) {
        Integer uid = WmThreadLocalUtils.getUser().getId();
        //1.参数检查
        if (wmNewsPageReqDto == null) {
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL, "参数为空");
        }
        //分页初始化 检查
        wmNewsPageReqDto.checkParam();
        // 根据条件进行判断
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WmNews::getUserId,uid);  // 只查询当前用户下的文章信息
        //状态
        lambdaQueryWrapper.eq(wmNewsPageReqDto.getStatus() != null, WmNews::getStatus, wmNewsPageReqDto.getStatus());
        //关键字
        lambdaQueryWrapper.like(null != wmNewsPageReqDto.getKeyword(), WmNews::getTitle, wmNewsPageReqDto.getKeyword());
        // 频道ID
        lambdaQueryWrapper.eq(wmNewsPageReqDto.getChannelId() != null, WmNews::getChannelId, wmNewsPageReqDto.getChannelId());
        // 时间查询
        // 大于等于 gt/gte ge 小于等于  le lte lt       区间查询（前端设计需求）
//        lambdaQueryWrapper.ge(wmNewsPageReqDto.getBeginPubDate()!=null,WmNews::getPublishTime,wmNewsPageReqDto.getBeginPubDate());
//        lambdaQueryWrapper.le(wmNewsPageReqDto.getEndPubDate()!=null,WmNews::getPublishTime,wmNewsPageReqDto.getEndPubDate());

        lambdaQueryWrapper.between(wmNewsPageReqDto.getBeginPubDate() != null && wmNewsPageReqDto.getEndPubDate() != null, WmNews::getPublishTime, wmNewsPageReqDto.getBeginPubDate(), wmNewsPageReqDto.getEndPubDate());

        IPage<WmNews> iPage = this.page(new Page<>(wmNewsPageReqDto.getPage(),wmNewsPageReqDto.getSize()),lambdaQueryWrapper);
        ResponseResult responseResult = new PageResponseResult(wmNewsPageReqDto.getPage(),wmNewsPageReqDto.getSize(),(int)iPage.getTotal());
        responseResult.setData(iPage.getRecords());
        return responseResult;
    }


//    文章发布
    @Override
    @Transactional
    public ResponseResult saveNews(WmNewsDto dto, Short isSubmit) {
        //1.检查参数
        if (dto == null) {
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL, "参数为空");
        }
        WmNews wmNews = new WmNews();
        //Spring提供的复制属性
        BeanUtils.copyProperties(dto, wmNews);
        if (WemediaContans.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null);
        }
        // 转换前端传递到后端的图片  前端是数组类型 但是 数据库使用的是字符串类型中间使用,拼接
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            String images = "";
            for (String image : dto.getImages()) {
                images += image + ",";
            }
            wmNews.setImages(images.substring(0, images.length() - 1));
        }
        //2.保存或修改文章（wm_news）
        saveWmNews(wmNews,isSubmit);
        //3.关联文章与素材的关系
        String content = dto.getContent();
        // List<Map>
        List<Map> list = JSON.parseArray(content, Map.class);
        //素材集合 获取内容中的素材
        List<String> materials =  pickUpImageUrl(list);
        //3.1 关联内容中的图片与素材的关系（wm_news_material）  必须是发布状态才能进行保存关系
        if(WmNews.Status.SUBMIT.getCode() == isSubmit && materials.size() != 0){
            saveRelativeInfoForNR(materials,wmNews.getId());
        }
        //3.2 关联封面中的图片与素材的关系,设置wm_news的type,自动（wm_news_material）
        if(WmNews.Status.SUBMIT.getCode() == isSubmit){
            saveRelativeInfoForFM(dto,materials,wmNews);   //必须是发布状态才能进行保存关系
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }



    /**
     * 保存素材与文章关系（内容）
     */
    private void saveRelativeInfoForNR(List<String> materials,Integer newsId){
        //内容引用
        saveRelativeInfo(materials,newsId,WemediaContans.WM_CONTENT_REFERENCE);
    }

    /**
     * 保存封面与文章关系（封面）
     */
    private void saveRelativeInfoForFM(WmNewsDto dto, List<String> materials, WmNews wmNews){
        // [asdfasdfasdf,asdfasdfasdf,asdfasdfasdf]
        List<String> images = dto.getImages();
        // 判断 前端传递的类型  自动类型  -1
        if(WemediaContans.WM_NEWS_TYPE_AUTO.equals(dto.getType())){
            //自动获取封面
            if(materials!=null && materials.size()>0 && materials.size()<=2){
                // 单图
                wmNews.setType(WemediaContans.WM_NEWS_SINGLE_IMAGE);
                images = materials.stream().limit(1).collect(Collectors.toList());
            }else if(materials!=null && materials.size()>2){
                //三图
                wmNews.setType(WemediaContans.WM_NEWS_MANY_IMAGE);
                images = materials.stream().limit(3).collect(Collectors.toList());
            }else{
                //无图
                wmNews.setType(WemediaContans.WM_NEWS_NONE_IMAGE);
            }
        }
        // 转换前端传递到后端的图片  前端是数组类型 但是 数据库使用的是字符串类型中间使用,拼接
        if (images != null && images.size() > 0) {
            String image = "";
            for (String item : images) {
                image += item + ",";
            }
            wmNews.setImages(image.substring(0, image.length() - 1));
        }
        //修改WmNews 状态  因为 最开始的时候 保存了数据库了 在这个地方进行修改状态
        this.updateById(wmNews);
        // 主图引用 保存关系
        if (images != null && images.size() > 0) {
            saveRelativeInfo(images,wmNews.getId(),WemediaContans.WM_COVER_REFERENCE);
        }
    }




    /**
     * 保存素材与文章信息
     */
    private void saveRelativeInfo(List<String> materials, Integer newsId, Short type){
        materials = materials.stream().map(i -> {
            i = i.replace("http://192.168.211.132:8080/", "");
            return i;
        }).collect(Collectors.toList());
        //1. 获取数据库中的素材信息
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(WmMaterial::getUrl,materials);
        lambdaQueryWrapper.eq(WmMaterial::getUserId,WmThreadLocalUtils.getUser().getId());
        List<WmMaterial> list =  wmMaterialMapper.selectList(lambdaQueryWrapper);
        //2. 通过图片路径获取图片Id
        Map<String,Integer> map =  list.stream().collect(Collectors.toMap(WmMaterial::getUrl,WmMaterial::getId));
        List<String> materialIds = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (String url : materials) {
                String materialId = String.valueOf(map.get(url));
                //没找到
                if ("null".equals(materialId)) {
                    CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"图片有问题");
                }
                materialIds.add(materialId);
            }
        }
        //3. 批量保存
        wmNewsMaterialMapper.saveRelationsByContent(materialIds,newsId,type);
    }




    /**
     * 提取内容中的素材路径
     */
    private List<String> pickUpImageUrl(List<Map> list){
        List<String> materials = new ArrayList<>();
        for (Map map:list){
            // type==image
            if(map.get("type").equals(WemediaContans.WM_NEWS_TYPE_IMAGE)){
                materials.add((String) map.get("value"));
            }
        }
        return materials;
    }


    /**
     * 保存或者修改文章
     */
    public void saveWmNews(WmNews wmNews,Short isSubmit){
        wmNews.setStatus(isSubmit);  // 发布或者草稿
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short)1); // 默认下架状态  因为还没有审核

        boolean flag=false;
        if(wmNews.getId() == null){
            //保存
            flag=save(wmNews);
        }else{
            //修改  删除素材和文章的关系
            LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(WmNewsMaterial::getNewsId,wmNews.getId());
            wmNewsMaterialMapper.delete(lambdaQueryWrapper);
            flag=updateById(wmNews);
        }
        if (flag){
            rabbitTemplate.convertAndSend("adminExchange","admin",wmNews.getId());
        }
    }

    /**
     * 根据ID 查询对应的文章信息
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1.参数检查
        if(id == null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"文章Id不可缺少");
        }
        WmNews wmNews =  this.getById(id);
        if(wmNews == null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"文章不存在");
        }
        //3.结果返回
        ResponseResult responseResult = ResponseResult.okResult(wmNews);
        return responseResult;
    }

    @Override
    @Transactional
    public ResponseResult delNews(Integer id) {
        //1.参数检查
        if(id == null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"文章Id不可缺少");
        }
        //2.查询文章信息 获取文章信息中的 状态以及上下架状态
        WmNews wmNews =  this.getById(id);
        if(wmNews == null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"文章不存在");
        }
        // 判断发布状态 == 9 并且 上架状态 == 1 不能删除
        if(wmNews.getStatus() == WmNews.Status.PUBLISHED.getCode() && wmNews.getEnable() == WemediaContans.WM_NEWS_ENABLE_UP){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"当前已发布文章状态不能删除，请下架后重试");
        }
        // 删除关联关系
        wmNewsMaterialMapper.delete(new LambdaQueryWrapper<WmNewsMaterial>().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
        // 删除自己
        this.removeById(id);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        // status == 9
        //1.参数检查
        if(dto == null || dto.getId() == null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"参数不能为空");
        }
        //2.查询文章信息 获取文章信息中的 状态以及上下架状态
        WmNews wmNews =  this.getById(dto.getId());
        if(wmNews == null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"文章不存在");
        }
        //3.判断文章是否发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"当前文章不是发布状态，不能上下架");
        }
        //4.修改文章状态，同步到app端（后期做）  --> article 数据库中
        if(dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2){
            update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId()).set(WmNews::getEnable,dto.getEnable()));
            Map map=new HashMap();
            map.put("article_id",wmNews.getArticleId());
            map.put("enable",dto.getEnable());
            rabbitTemplate.convertAndSend("DownOrUpExange","downUp",map);
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    @Override
    public List<Integer> findRelease() {
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<WmNews>();
        // 状态 = 8
        lambdaQueryWrapper.eq(WmNews::getStatus, 8);
        //已经到时间了
        lambdaQueryWrapper.le(WmNews::getPublishTime,new Date());
        List<WmNews> list =  list(lambdaQueryWrapper);
        List<Integer> ids =  list.stream().map(WmNews::getId).collect(Collectors.toList());
        return ids;
    }

    @Override
    public PageResponseResult findListAndPage(NewsAuthDto dto) {
        //1 检查参数
        if(dto==null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"有问题");
        }
        //2. 初始化分页
        dto.checkParam();
        dto.setPage((dto.getPage()-1)*dto.getSize());
        if(dto.getTitle()!=null && !"".equals(dto.getTitle())){
            dto.setTitle("%"+dto.getTitle()+"%");
        } // 会导致索引失效
        List<WmNewsVo> list =  wmNewsMapper.findListAndPage(dto);
        Integer total = wmNewsMapper.findListCount(dto);
        PageResponseResult pageResponseResult = new PageResponseResult();
        pageResponseResult.setData(list);
        pageResponseResult.setCurrentPage(dto.getPage());
        pageResponseResult.setSize(dto.getSize());
        pageResponseResult.setTotal(total);
        return pageResponseResult;
    }

    @Autowired
    private WmUserMapper wmUserMapper;
    @Override
    public WmNewsVo findWmNewsVo(Integer id) {
        //1.查询文章信息
        WmNews wmNews = getById(id);
        //2.查询作者
        WmUser wmUser = null;
        if(wmNews!=null && wmNews.getUserId() != null){
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if(wmUser != null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        return wmNewsVo;
    }
}
